<?php

namespace app\stock\controller;

use think\Controller;

class Admin extends Controller
{
    private $AdminModel;

    public function _initialize()
    {
        // 继承父类
        parent::_initialize();
        $this->AdminModel = model('Admin');
    }
    // 账号登录
    public function login()
    {
        $username = $this->request->param('username', '', 'trim');
        $password = $this->request->param('password', '', 'trim');
        $admininfo = $this->AdminModel->where('username', $username)->find();
        if (!$admininfo) {
            $this->error("管理员不存在");
        }
        $password = md5(md5($password) . $admininfo['salt']);
        if ($admininfo['password'] != $password) {
            $this->error("密码错误");
        }
        if ($admininfo['status'] != 'normal') {
            $this->error("管理员已被禁用");
        }
        $data = [
            'id' => $admininfo['id'],
            'username' => $admininfo['username'],
            'nickname' => $admininfo['nickname'],
            'avatar' => $admininfo['avatar_text'],
            'group_text' => $admininfo['group_text'],
            'createtime' => $admininfo['createtime'],
            'email' => $admininfo['email'],
            'openid' => $admininfo['openid'],
        ];
        $this->success('登录成功', "", $data);
    }
    // 授权登录
    public function authorization()
    {
        $code = $this->request->param('code', '', 'trim');
        $adminid = $this->request->param('adminid', 0, 'trim');
        if ($code) {
            $openid = $this->authlogin($code);
            if ($openid) {
                if ($adminid == 0) {
                    $admininfo = $this->AdminModel->where('openid', $openid)->find();
                    if ($admininfo) {
                        $data = [
                            'id' => $admininfo['id'],
                            'username' => $admininfo['username'],
                            'nickname' => $admininfo['nickname'],
                            'avatar' => $admininfo['avatar_text'],
                            'group_text' => $admininfo['group_text'],
                            'createtime' => $admininfo['createtime'],
                            'email' => $admininfo['email'],
                            'openid' => $admininfo['openid'],
                        ];

                        $this->success('授权登陆成功', '', $data);
                    } else {
                        $this->error('未绑定帐号，请先去绑定');
                    }
                } else {
                    $admininfo = $this->AdminModel->find($adminid);
                    if (!$admininfo) {
                        $this->error('管理员不存在');
                    }
                    $result = $this->AdminModel->isUpdate()->save(['openid' => $openid, 'id' => $adminid]);
                    if($result==false) {
                        $this->error("绑定失败");
                    }else{
                        $data = [
                            'id' => $admininfo['id'],
                            'username' => $admininfo['username'],
                            'nickname' => $admininfo['nickname'],
                            'avatar' => $admininfo['avatar_text'],
                            'group_text' => $admininfo['group_text'],
                            'createtime' => $admininfo['createtime'],
                            'email' => $admininfo['email'],
                            'openid' => $openid,
                        ];
                        $this->success('绑定成功', "", $data);
                    }
                }
            } else {
                $this->error('登录凭证校验失败');
            }
        } else {
            $this->error("临时登录凭证 code没有");
        }
    }
    // 绑定账号
    public function bind()
    {
        $code = $this->request->param('code', '', 'trim');
        $username = $this->request->param('username', '', 'trim');
        $password = $this->request->param('password', '', 'trim');
        $admininfo = $this->AdminModel->where('username', $username)->find();
        if (!$admininfo) {
            $this->error("管理员不存在");
        }
        $password = md5(md5($password) . $admininfo['salt']);
        if ($admininfo['password'] != $password) {
            $this->error("密码错误");
        }
        if ($admininfo['status'] != 'normal') {
            $this->error("管理员已被禁用");
        }
        $openid = $this->authlogin($code);
        if ($openid) {
            $result = $this->AdminModel->isUpdate()->save(['openid' => $openid, 'id' => $admininfo['id']]);
            if ($result === false) {
                $this->error("绑定失败");
            } else {
                $data = [
                    'id' => $admininfo['id'],
                    'username' => $admininfo['username'],
                    'nickname' => $admininfo['nickname'],
                    'avatar' => $admininfo['avatar_text'],
                    'group_text' => $admininfo['group_text'],
                    'createtime' => $admininfo['createtime'],
                    'email' => $admininfo['email'],
                    'openid' => $openid,
                ];
                $this->success('绑定成功', "", $data);
            }
        } else {
            $this->error('登录凭证校验失败');
        }
    }
    // 登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程。更多使用方法详见小程序登录。
    public function authlogin($code = null)
    {
        // 小程序 appId
        $appid = "wxc4fb5251b16d12e7";
        // 小程序 appSecret
        $secret = "5c1559326a66771508dc52dfad0218d9";

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";

        $result = httpRequest($url);
        $result = json_decode($result, true);
        if (isset($result['openid']) && $result['openid']) {
            return $result['openid'];
        }
        return false;
    }
    // 修改个人资料
    public function profile()
    {
        $params = $this->request->param();
        $adminid = $params['adminid'] ?? 0;
        $password = $params['password'] ?? '';

        $admininfo = $this->AdminModel->find($adminid);

        if (!$admininfo) {
            $this->error('管理员不存在');
        }

        $adminData = [
            'id' => $adminid,
            'email' => $params['email'],
            'nickname' => $params['nickname'],
        ];

        // 判断是否修改密码
        if ($password) {
            $adminData['password'] = md5(md5($password) . $admininfo['salt']);
        }
        if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {
            $res = upload('avatar');
            if ($res['code'] == 0) {
                $this->error($res['msg']);
            }
            $adminData['avatar'] = $res['data'];
        }
        $result = $this->AdminModel->isUpdate()->save($adminData);
        if ($result === false) {
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {
                $path = ltrim($adminData['avatar'], '/');
                is_file($path) && unlink($path);
            }
            $this->error("修改失败");
        } else {
            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0 && $_FILES['avatar']['error'] == 0) {
                if ($admininfo['avatar']) {
                    // 删除旧的图片
                    $path = ltrim($admininfo['avatar'], '/');
                    is_file($path) && unlink($path);
                }
            }

            $admininfo = $this->AdminModel->find($adminid);

            $data = [
                'id' => $admininfo['id'],
                'username' => $admininfo['username'],
                'nickname' => $admininfo['nickname'],
                'avatar' => $admininfo['avatar_text'],
                'group_text' => $admininfo['group_text'],
                'createtime' => $admininfo['createtime'],
                'email' => $admininfo['email'],
                'openid' => $admininfo['openid']
            ];
            $this->success('修改成功', '', $data);
        }
    }
    // 解绑
    public function unbind()
    {
        $adminid = $this->request->param('adminid', 0, 'trim');
        $admininfo = $this->AdminModel->find($adminid);
        if (!$admininfo) {
            $this->error('管理员不存在');
        }
        $result = $this->AdminModel->isUpdate()->save(['openid' => '', 'id' => $adminid]);
        if ($result === false) {
            $this->error("微信解绑失败");
        }
        $data = [
            'id' => $admininfo['id'],
            'username' => $admininfo['username'],
            'nickname' => $admininfo['nickname'],
            'avatar' => $admininfo['avatar_text'],
            'group_text' => $admininfo['group_text'],
            'createtime' => $admininfo['createtime'],
            'email' => $admininfo['email'],
            'openid' => '',
        ];
        $this->success('解绑成功！','',$data);
    }
}
